const { Service } = require('dx-router-admin');
const { UniIdDevice } = require('dx-func-entity');

module.exports = class Device extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = UniIdDevice;
	}
	async saveDevice(pushClientId) {
		const context = this.$dx.request.context;
		const deviceId = context.deviceId,
			appId = context.appId,
			osName = context.osName;
		let platform = context.PLATFORM || context.uniPlatform;
		if (platform === 'app') {
			platform += osName;
		}
		const device = await this.where('device_id', deviceId).find();
		await this.$dx.service.openDevice.saveDevice(pushClientId);
		const data = {
			user_id: this.$dx.auth.uid,
			device_id: deviceId,
			token_expired: this.$dx.request.tokenExpired(),
			push_clientid: pushClientId,
			appid: appId,
		};
		if (!device) {
			data.create_date = Date.now();
			data.ua = context.ua || context.CLIENTUA;
			data.os_name = osName;
			data.os_version = context.osVersion;
			data.model = context.model;
			data.platform = platform;
		} else {
			data._id = device._id;
		}
		await this.save(data);
	}
};
